package com.example.yaseademo;

import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.github.faucamp.simplertmp.RtmpHandler;
import com.seu.magicfilter.utils.MagicFilterType;

import net.ossrs.yasea.SrsCameraView;
import net.ossrs.yasea.SrsEncodeHandler;
import net.ossrs.yasea.SrsPublisher;
import net.ossrs.yasea.SrsRecordHandler;

import java.io.IOException;
import java.net.SocketException;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;

public class StreamingActivity extends AppCompatActivity implements SrsEncodeHandler.SrsEncodeListener
        , SrsRecordHandler.SrsRecordListener, RtmpHandler.RtmpListener, View.OnClickListener {
    SrsPublisher mPublisher;
    EditText et_address;
    Button btn_start;
    public static String TAG = StreamingActivity.class.getName();
    private Button btn_switch;
    private boolean isBackFace = false;
    private Spinner spinner;
    final MagicFilterType[] filterTypes = {MagicFilterType.NONE, MagicFilterType.HEALTHY, MagicFilterType.SUNRISE,
            MagicFilterType.SUNSET, MagicFilterType.WHITECAT, MagicFilterType.BLACKCAT, MagicFilterType.SKINWHITEN, MagicFilterType.BEAUTY};
    private SrsCameraView cameraView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_streaming);

        initView();
        initPublisher(cameraView);

        NetworkSpeedChecker.INSTANCE.getNetSpeed(this, 1, (Function1<Long, Unit>) aLong -> {
            if (BuildConfig.DEBUG) Log.d("getNetSpeed", aLong/1024 + " kb/s");
            return null;
        });
    }

    private void initView() {
        cameraView = (SrsCameraView) findViewById(R.id.glsurfaceview_camera);
        et_address = findViewById(R.id.et_address);
        btn_start = findViewById(R.id.btn_start);
        final String url = "rtmp://live-push.bilivideo.com/live-bvc/?streamname=live_36129635_68290194&key=5be2b9eb5d68043fcdd467333d0e7e85";
        btn_start.setOnClickListener((v) -> mPublisher.startPublish(url /*et_address.getText().toString().trim()*/));

        //开始推流 rtmpUrl（ip换成服务器的部署ip）："rtmp://192.168.31.126/android/teststream"
        btn_switch = (Button) findViewById(R.id.btn_switch);
        btn_switch.setOnClickListener(this);

        spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mPublisher.switchCameraFilter(filterTypes[position]);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spinner.setSelection(0);
    }

    private void initPublisher(SrsCameraView cameraView) {
        mPublisher = new SrsPublisher(cameraView);
        //编码状态回调
        mPublisher.setEncodeHandler(new SrsEncodeHandler(this));
        mPublisher.setRecordHandler(new SrsRecordHandler(this));
        //rtmp推流状态回调
        mPublisher.setRtmpHandler(new RtmpHandler(this));
        //预览分辨率
        mPublisher.setPreviewResolution(1280, 720);
        //推流分辨率
        mPublisher.setOutputResolution(720, 1280);
        //传输率
        mPublisher.setVideoHDMode();
        //开启美颜（其他滤镜效果在MagicFilterType中查看）
        // mPublisher.switchCameraFilter(MagicFilterType.BEAUTY);
        //打开摄像头，开始预览（未推流）
//        mPublisher.startCamera();
//        mPublisher.startAudio();

        mPublisher.switchCameraFace(Camera.CameraInfo.CAMERA_FACING_BACK);
//        mPublisher.switchToSoftEncoder();//选择软编码
        mPublisher.switchToHardEncoder();//选择硬编码
    }

    @Override
    public void onNetworkWeak() {
        Log.d(TAG, "onNetworkWeak: ");
    }

    @Override
    public void onNetworkResume() {
        Log.d(TAG, "onNetworkResume: ");
    }

    @Override
    public void onEncodeIllegalArgumentException(IllegalArgumentException e) {

    }

    @Override
    public void onRecordPause() {

    }

    @Override
    public void onRecordResume() {

    }

    @Override
    public void onRecordStarted(String msg) {
        Log.d(TAG, "onRecordStarted: " + msg);
    }

    @Override
    public void onRecordFinished(String msg) {
        Log.d(TAG, "onRecordFinished: " + msg);
    }

    @Override
    public void onRecordIllegalArgumentException(IllegalArgumentException e) {

    }

    @Override
    public void onRecordIOException(IOException e) {

    }

    @Override
    public void onRtmpConnecting(String msg) {

    }

    @Override
    public void onRtmpConnected(String msg) {

    }

    @Override
    public void onRtmpVideoStreaming() {

    }

    @Override
    public void onRtmpAudioStreaming() {

    }

    @Override
    public void onRtmpStopped() {

    }

    @Override
    public void onRtmpDisconnected() {

    }

    @Override
    public void onRtmpVideoFpsChanged(double fps) {
        Log.d("onRtmpVideoFpsChanged", "FPS" + fps);
    }

    @Override
    public void onRtmpVideoBitrateChanged(double bitrate) {

    }

    @Override
    public void onRtmpAudioBitrateChanged(double bitrate) {

    }

    @Override
    public void onRtmpSocketException(SocketException e) {

    }

    @Override
    public void onRtmpIOException(IOException e) {

    }

    @Override
    public void onRtmpIllegalArgumentException(IllegalArgumentException e) {

    }

    @Override
    public void onRtmpIllegalStateException(IllegalStateException e) {

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mPublisher.resumePublish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPublisher.pausePublish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPublisher.stopPublish();
        NetworkSpeedChecker.INSTANCE.cancelJob();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_switch:
                //  mPublisher.pausePublish();
                isBackFace = !isBackFace;
                if (isBackFace) {
                    mPublisher.switchCameraFace(Camera.CameraInfo.CAMERA_FACING_FRONT);
                } else {
                    mPublisher.switchCameraFace(Camera.CameraInfo.CAMERA_FACING_BACK);
                }
                // mPublisher.resumePublish();
                break;
        }
    }
}
